package com.example.file.security.support;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.file.exception.ServiceException;
import com.example.file.response.ResultEnum;
import com.example.file.security.utils.JwtUtils;
import lombok.AllArgsConstructor;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * JwtVerifyHandler class
 *
 * @author Erik Amaru Ortiz
 */
public class JwtVerifyHandler {


    public Mono<VerificationResult> check(String accessToken) {

        verify(accessToken);
        return Mono.just(accessToken).map(this::verify)
                .onErrorResume(e -> {
                    return Mono.error(new RuntimeException(e.getMessage()));
                });
    }

    private VerificationResult verify(String token) {

        DecodedJWT tokenInfo = null;
        try {
            tokenInfo = JwtUtils.getTokenInfo(token);
        } catch (Throwable e) {
            throw new ServiceException(ResultEnum.CLEAN_TOKEN);
        }

        return new VerificationResult(tokenInfo.getClaims(), token);
    }


    @AllArgsConstructor
    public static class VerificationResult {
        public Map<String, Claim> claims;
        public String token;
    }
}

